<?php

namespace common\service;

use common\model\DelayOrderTaskModel;
use common\model\EntityModel;
use common\model\ProjectStepCategoryConfirmConfigModel;
use common\model\ReviewFeedbackEntityModel;
use common\model\ReviewFeedbackModel;
use common\model\TaskWorkOrderModel;
use support\SingletonTrait;
use think\Db;

class DemandChangeService
{
    use SingletonTrait;

    /**
     * 需求单字段
     * @var string[]
     */
    public $demandOrderField;

    /**
     * 工单字段
     * @var string[]
     */
    public $taskWorkOrderField;

	public $delayOrderTask;

    public function __construct()
    {
        $remakeStatusId = StatusService::getInstance()->getTaskDefaultRemakeStatus()['id'];
        $this->demandOrderField = [
            "count(rfe.is_append = 'yes' or null) append", // 新增数量
            "count(JSON_UNQUOTE(JSON_EXTRACT(task.json, '$.task_status')) = $remakeStatusId or null) remake", // 返修数量
            "count(rfe.enable = 'no' or null) abo", // 废除数量
            "rf.title", // 变更来源
            "JSON_UNQUOTE(JSON_EXTRACT(rf.json,'$.invoke_department_man')) as invoke_department_man", // 提出人-部门和用户
            "JSON_UNQUOTE(JSON_EXTRACT(rf.json,'$.invoke_description')) as invoke_description", // 提出原因
            'rf.demand_type as type', // tag [需求单][工单]
            'rf.step_category_ids',// 提出环节
            'rf.id'
        ];
        $this->taskWorkOrderField = [
            '0 append',
            'count(distinct roat.task_id) as remake',
            '0 abo',
            'two.report_content title',
            "json_set('[]', '$[0]',json_set('{}', '$.department_id', task.department_id, '$.user_id', 0)) invoke_department_man",
            'two.report_content invoke_description',
            "'task_work_order' as type",
            'two.step_category_id step_category_ids',
            'two.id'
        ];

		$this->delayOrderTask = model(DelayOrderTaskModel::class);
    }

    /**
     * 需求变更列表
     * @param $data
     * @param $page
     * @return array
     */
    public function list($data, $page)
    {
        $demandOrderSql = model(EntityModel::class)->field($this->demandOrderField)
            ->join('review_feedback_entity rfe on rfe.entity_id = entity.id')
            ->join('review_feedback rf on rf.id = rfe.review_feedback_id')
            ->join('task on task.entity_id = entity.id')
            ->where(['entity.project_id' => $data['project_id']])
//            ->where(['entity.module_id' => ['IN', [module_by_code('asset')['id'], module_by_code('shot')['id']]]])
            ->where(['entity.created' => ['BETWEEN', [$data['start_time'], $data['end_time']]]])
            ->where(['task.project_id' => $data['project_id']])
            ->where(['rf.project_id' => $data['project_id'], 'rf.demand_type' => 'demand_order'])
            ->where(['rfe.published' => ReviewFeedbackEntityModel::PUBLISHED_YES])
            ->group('rf.demand_order_id')
            ->buildSql();

        $taskWorkOrderSql = model(TaskWorkOrderModel::class)
            ->alias('two')->field($this->taskWorkOrderField)
            ->join('repair_task_work_order_relation rtwor on two.id = rtwor.task_work_order_id')
            ->join('task_repair_order tro on rtwor.task_repair_order_id = tro.id')
            ->join('repair_order_affected_task roat on tro.id = roat.task_repair_order_id')
            ->join('task on task.id = two.task_id')
//            ->where(['task_work_order.type' => TaskWorkOrderModel::TYPE_REVIEW_FEEDBACK])
            ->where(['two.project_id' => $data['project_id']])
            ->where(['two.created' => ['BETWEEN', [$data['start_time'], $data['end_time']]]])
            ->group('two.id')
            ->buildSql();

        $limit = $page[1] * ($page[0] - 1);
        $pageSize = $page[1];
        $data = Db::query($demandOrderSql . 'union' . $taskWorkOrderSql . 'limit ' . "$limit,$pageSize");
        if (empty($data)) {
            return [];
        }
        return array_map(function ($tmp) {
            $tmp['invoke_department_man'] = json_decode($tmp['invoke_department_man'], true);
            $tmp['step_category_ids'] = array_map('intval', explode(',', $tmp['step_category_ids']));
            return $tmp;
        }, $data);
    }

    /**
     * 需求单任务ids
     * @param $abnormalType
     * @param $projectId
     * @param $startTime
     * @param $endTime
     * @return array|mixed|string
     */
    public function getTaskList($abnormalType, $projectId, $startTime, $endTime)
    {
        $dbr = model(EntityModel::class)
            ->field('task.id as task_id')
            ->join('review_feedback_entity rfe on rfe.entity_id = entity.id')
            ->join('review_feedback rf on rf.id = rfe.review_feedback_id')
            ->join('task on task.entity_id = entity.id');
        // 废除
        if (!empty($abnormalType == 'abo')) {
            $dbr->where(['rfe.enable' => 'no']);
        }
        // 新增
        if (!empty($abnormalType == 'append')) {
            $dbr->where(['rfe.is_append' => 'yes']);
        }
        // 返修
        if (!empty($abnormalType == 'repair')) {
            $remakeStatusId = StatusService::getInstance()->getTaskDefaultRemakeStatus()['id'];
            $dbr->where(["JSON_UNQUOTE(JSON_EXTRACT(`task`.`json`, '$.task_status'))" => $remakeStatusId]);
        }
        if (!empty($projectId)) {
            $dbr->where(['entity.project_id' => $projectId])
                ->where(['task.project_id' => $projectId])
                ->where(['rf.project_id' => $projectId]);
        }
        if (!empty($startTime) && !empty($endTime)) {
            $dbr->where(['entity.created' => ['BETWEEN', [$startTime, $endTime]]]);
        }
        $demandOrderList = $dbr
//            ->where(['entity.module_id' => ['IN', [module_by_code('asset')['id'], module_by_code('shot')['id']]]])
            ->where(['rf.demand_type' => 'demand_order'])
            ->where(['rfe.published' => ReviewFeedbackEntityModel::PUBLISHED_YES])
            ->column('task_id');
        if (empty($demandOrderList)) {
            return [];
        }
        return $demandOrderList;
    }

	/**
	 * 工作台-我的任务-工作待办-需求单统计
	 * @param array $param
	 * @return array|void
	 */
	public function getDemandOrderListStatistics(array $param = [],int $userId)
	{
		//组装需求单数据
		$condition = [
            "rf.demand_type" => "demand_order",
            "ps_ccc.type" => ProjectStepCategoryConfirmConfigModel::TYPE_DEMAND_ORDER_CONFIRM,
            "_string" => "rfc.id is null",
            "rf.status" => "in_progress",
        ];
		//待我确认的需求单数据
		$result = model(ReviewFeedbackModel::class)->alias('rf')
			->field("count(distinct rf.id) num")
			->join("review_feedback_entity rfe on rfe.review_feedback_id = rf.id")
			->join("note_entity_relation ner on ner.review_feedback_id = rf.id")
			->join("
				project_step_category_confirm_config ps_ccc
				ON rf.project_id = ps_ccc.project_id
				and ner.step_category_id = ps_ccc.step_category_id
				and ps_ccc.confirm_user_id = {$userId}
				")
			->join("review_feedback_confirm rfc on rfc.review_feedback_id = rf.id and rfc.user_id = {$userId}","left")
			->where($condition)
			->select();

		if(empty($result)){
			return ['num' => 0];
		}

		return ['num' => $result[0]['num']];
	}
}
